package com.example.administrator.managesystem.activity.my_profile.typein;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.managesystem.R;
import com.example.administrator.managesystem.activity.firstpage.circle.ui.SendCircleActivity;
import com.example.administrator.managesystem.adapter.GridImageAdapter;
import com.example.administrator.managesystem.bean.CameraListBean;
import com.example.administrator.managesystem.bean.GetCameraBean;
import com.example.administrator.managesystem.bean.LandListBean;
import com.example.administrator.managesystem.bean.TagBean;
import com.example.administrator.managesystem.manager.FullyGridLayoutManager;
import com.example.administrator.managesystem.manager.RxManager;
import com.example.administrator.managesystem.ui.AddLandView;
import com.example.administrator.managesystem.utils.ConstantUtil;
import com.example.administrator.managesystem.utils.LogUtil;
import com.example.administrator.managesystem.utils.StatusBarUtil;
import com.example.administrator.managesystem.utils.ToastUtils;
import com.example.administrator.managesystem.view.MyDialogFragment;
import com.example.administrator.managesystem.view.NoDoubleClickListener;
import com.example.administrator.managesystem.view.TimePickerDialog;
import com.example.administrator.managesystem.view.WheelDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class TypeInCodeActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks , AddLandView {
    private static final int REQUEST_CODE_QRCODE_PERMISSIONS = 1;
    private List<LocalMedia> selectList = new ArrayList<>();
    private List<String> list_seleted=new ArrayList<>();
    private RecyclerView recyclerView;
    private GridImageAdapter adapter;
    private int maxSelectNum = 9;
    private int themeId;
    protected RxManager mRxManager;
    private TextView scan_tv,submit;
    private List<String> labels_id;
    private List<String> datas ;
    private EditText code_et,goods_et,phone_et,area_et,time_et,number_et,name_et;
    private String label_id;
    private TypePresenter typePresenter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_type_in);
        code_et=findViewById(R.id.code_tv);
        scan_tv=findViewById(R.id.test_scan_qrcode);
        goods_et=findViewById(R.id.goods_et);
        phone_et=findViewById(R.id.phone_et);
        area_et=findViewById(R.id.area_et);
        time_et=findViewById(R.id.time_et);
        number_et=findViewById(R.id.number_et);
        submit=findViewById(R.id.submit_tv);
        name_et=findViewById(R.id.name_et);

        typePresenter=new TypePresenter(this);
        //状态栏
        mRxManager = new RxManager();
        StatusBarUtil.setWindowStatusBarColor(this,R.color.color_yellow);
        //竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        themeId = R.style.picture_default_style;
        recyclerView =  findViewById(R.id.recycler);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                LocalMedia media = selectList.get(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片
                        PictureSelector.create(TypeInCodeActivity.this).externalPicturePreview(position, selectList);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(TypeInCodeActivity.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(TypeInCodeActivity.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        });


        mRxManager.on(ConstantUtil.UPDATE_CODE, new Consumer<String>() {
            @Override
            public void accept(String code) throws Exception {
                LogUtil.e("ConstantUtil.UPDATE_CODE --- code" + code);
                ToastUtils.showToast(TypeInCodeActivity.this,code);
                if(code.isEmpty()) return;
                String[] split = code.split("/");
                String content = split[split.length-1];
                code_et.setText(content);
            }
        });
        scan_tv.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
               Intent intent=new Intent(TypeInCodeActivity.this,CodeScanActivity.class);
               startActivity(intent);

            }
        });

        goods_et.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                typePresenter.goodsTypeRequest(TypeInCodeActivity.this);

            }
        });

        time_et.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                TimePickerDialog.init().setTimeClickListener(new TimePickerDialog.TimeClickListener() {
                    @Override
                    public void onClick(String day, String time) {
                       time_et.setText(day);
                    }
                }).showDialog(TypeInCodeActivity.this,"");

            }
        });

        submit.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                list_seleted.clear();
                for(int i=0;i<selectList.size();i++){
                    list_seleted.add(selectList.get(i).getCompressPath());
                }
                Log.e("msg","list_seleted:"+list_seleted);

                if(list_seleted.isEmpty()){
                    ToastUtils.showToast(TypeInCodeActivity.this,"至少上传一张图片！");
                    return;
                }
                typePresenter.uploadTraces(TypeInCodeActivity.this,label_id,name_et.getText().toString(),phone_et.getText().toString(),area_et.getText().toString(),
                        time_et.getText().toString(),code_et.getText().toString(),Integer.parseInt(number_et.getText().toString()),list_seleted);
            }
        });


    }
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(TypeInCodeActivity.this)
                    .openGallery(PictureMimeType.ofImage())
                    .imageFormat(PictureMimeType.PNG)
                    .previewImage(true)// 是否可预览图片
                    .theme(themeId)
                    .maxSelectNum(9)
                    .minSelectNum(1)
                    .selectionMode(PictureConfig.MULTIPLE)
                    .previewVideo(true)
                    .enablePreviewAudio(true) // 是否可播放音频
                    .isCamera(true)
                    .compress(true)
                    .glideOverride(160, 160)
                    .minimumCompressSize(100)// 小于 100kb 的图片不压缩
                    .cropCompressQuality(90)// 裁剪压缩质量 默认100
                    .selectionMedia(selectList)
                    .forResult(PictureConfig.CHOOSE_REQUEST);

        }
    };



    @Override
    protected void onStart() {
        super.onStart();
        requestCodeQRCodePermissions();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
    }

    @AfterPermissionGranted(REQUEST_CODE_QRCODE_PERMISSIONS)
    private void requestCodeQRCodePermissions() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "扫描二维码需要打开相机和散光灯的权限", REQUEST_CODE_QRCODE_PERMISSIONS, perms);
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mRxManager != null)
            mRxManager.clear();
        super.onDestroy();
    }

    @Override
    public void showLandTag(List<TagBean.DataBean> list) {
        labels_id=new ArrayList<>();
        datas=new ArrayList<>();
        for (int i = 0; i <list.size() ; i++) {
            datas.add(list.get(i).getCategory_name());
            labels_id.add(list.get(i).getCategory_id());
        }

        WheelDialog.initDefault(datas, 12, new MyDialogFragment.ItemClickListener() {
            @Override
            public void onClick(int position) {
            goods_et.setText(datas.get(position));
            label_id=labels_id.get(position);
            }
        }). showDialog(TypeInCodeActivity.this, "MessageSettingDialog");
    }

    @Override
    public void showMsg() {

    }

    @Override
    public void showLandList(List<LandListBean.DataBean> list) {

    }

    @Override
    public void showDeleteMsg(String camera_id) {

    }

    @Override
    public void showCameraList(List<GetCameraBean.DataBean> list) {

    }

    @Override
    public void showCameraRecycler(List<CameraListBean.DataBean> list) {

    }

    @Override
    public void updateGrid() {

    }

    @Override
    public void showUrl(String url, String device_number) {

    }

    @Override
    public void showDelete(int position) {

    }

    @Override
    public void showErrMsg() {

    }

    @Override
    public void showToken(String token, String device_number) {

    }
}
